﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Globalization;

namespace RL
{
    

    /// <summary>
    /// Логика взаимодействия для wVehicleType.xaml
    /// </summary>
    public partial class wVehicleType : Window
    {


        public routelistEntities ContextDB
        {
            get { return (routelistEntities)GetValue(ContextDBProperty); }
            set { SetValue(ContextDBProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ContextDB.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ContextDBProperty =
            DependencyProperty.Register("ContextDB", typeof(routelistEntities), typeof(wVehicleType), new UIPropertyMetadata(null));




        public vehicle_type SelectedVehicleType
        {
            get { return (vehicle_type)GetValue(SelectedVehicleTypeProperty); }
            set { SetValue(SelectedVehicleTypeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedVehicleType.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedVehicleTypeProperty =
            DependencyProperty.Register("SelectedVehicleType", typeof(vehicle_type), typeof(wVehicleType), new UIPropertyMetadata(null));

        


        private RL.routelistEntities routelistEntities;
        public wVehicleType()
        {
            InitializeComponent();
        }

        private System.Data.Objects.ObjectQuery<vehicle_type> Getvehicle_typeQuery(routelistEntities routelistEntities)
        {
            // Автоматически созданный код

            System.Data.Objects.ObjectQuery<RL.vehicle_type> vehicle_typeQuery = routelistEntities.vehicle_type.Include("fuel_type");
            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // vehicle_typeQuery = vehicle_typeQuery.Include("vehicle_type.fuel_type").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Возвращает ObjectQuery.
            vehicle_typeQuery = vehicle_typeQuery.Include("FuelVehicleTypeNorm");
            return vehicle_typeQuery;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (null == ContextDB)
            {
                ContextDB = new RL.routelistEntities();
            }
            routelistEntities = ContextDB;
            // Загрузить данные в vehicle_type. Можно изменить этот код как требуется.
            System.Windows.Data.CollectionViewSource vehicle_typeViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicle_typeViewSource")));
            System.Data.Objects.ObjectQuery<RL.vehicle_type> vehicle_typeQuery = this.Getvehicle_typeQuery(routelistEntities);
            vehicle_typeViewSource.Source = vehicle_typeQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
            if (SelectedVehicleType != null)
            {
                vehicle_typeViewSource.View.MoveCurrentTo(SelectedVehicleType);
                vehicle_typeDataGrid.ScrollIntoView(SelectedVehicleType);
            }
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            SaveData();
        }

        private void buttonEdit_Click(object sender, RoutedEventArgs e)
        {
            CollectionViewSource cvs = (CollectionViewSource)this.Resources["vehicle_typeViewSource"];
            if (null == cvs) return;
            vehicle_type cur_item = cvs.View.CurrentItem as vehicle_type;
            OpenEditWindow(cur_item);
        }

        private bool IsModified()
        {
            bool bResult = false;
            if (null == routelistEntities) return false;
            bResult = routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Count() > 0 || routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Count() > 0 || routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Count() > 0;
            return bResult;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsModified())
            {
                var result = MessageBox.Show("Сохранить изменения?", "Предупреждение", MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Yes);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (false == SaveData())
                        {
                            e.Cancel = true;
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }

            }
        }

        private bool SaveData()
        {
            bool bResult = true;
            try
            {
                routelistEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Properties.Resources.DataSavingError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bResult = false;
            }
            return bResult;
        }

        private void buttonNew_Click(object sender, RoutedEventArgs e)
        {
            CollectionViewSource cvs = (CollectionViewSource)this.Resources["vehicle_typeViewSource"];
            if (null == cvs) return;
            BindingListCollectionView vw = cvs.View as BindingListCollectionView;
            fuel_type fuel = (from o in routelistEntities.fuel_type orderby o.name select o).FirstOrDefault();
            if (null == fuel)
            {
                MessageBox.Show("В системе не зарегистрирован ни один вид топлива. Созадть модель ТС невозможно.");
                return;
            }
            if (null == vw) return;
            vehicle_type item = (vehicle_type)vw.AddNew();
            item.name = "";
            item.id_main_fuel_type = fuel.id;
            item.type_vehicle = 1;
            item.heater = 0;
            item.del = false;
            vw.CommitNew();
        }

        private void OpenEditWindow(vehicle_type item)
        {
            try
            {
                wVehicleTypeItem wnd = new wVehicleTypeItem();
                if (null == item)
                {
                    wnd.VehicleTypeID = null;
                }
                else
                {
                    wnd.VehicleTypeID = item.id;
                }
                // wnd.ContextDB = routelistEntities;

                if (true == wnd.ShowDialog())
                {
                    routelistEntities.Refresh(System.Data.Objects.RefreshMode.StoreWins, item);
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            CollectionViewSource cvs = (CollectionViewSource)this.Resources["vehicle_typeViewSource"];
            if (cvs == null) return;
            vehicle_type item = cvs.View.CurrentItem as vehicle_type;
            SelectedVehicleType = item;
            try
            {
                DialogResult = true;
            }
            catch (Exception)
            {
                
            }
        }

        private string GetVehicleTypeByID(int id)
        {
            string result = "";
            XmlDataProvider xmlData = (XmlDataProvider)this.Resources["type_vehicle1"];
            xmlData.XPath = String.Format("[id={0}", id.ToString());
            object rsult = xmlData.Data;
            return result;
        }
    }

    [ValueConversion(typeof(int), typeof(String))]
    public class FuelTypeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (null == value) return "<не выбран>";
            int item_i = (int)value;
            routelistEntities db = new routelistEntities();
            fuel_type item = (from o in db.fuel_type where o.id == item_i select o).FirstOrDefault();
            if (null == item) return "";
            string result = string.Format("{0}", item.name);
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    [ValueConversion(typeof(int), typeof(String))]
    public class VehicleTypeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string result = "";
            int ivalue = (int)value;
            switch (ivalue)
            {
                case 1:
                    result = "автобус";
                    break;
                case 2:
                    result = "грузовой автомобиль";
                    break;
                case 3:
                    result = "легковой автомобиль";
                    break;
            }
            //XmlDataProvider xmlData = (XmlDataProvider)Application.Current.Resources["type_vehicle1"];
            //xmlData.IsInitialLoadEnabled = true;
            //xmlData.IsAsynchronous = false;
            //xmlData.Refresh();
            //int ivalue = (int)value;

            ////xmlData.XPath = String.Format("Typevehicle/Types/Type[@id={0}]", ivalue.ToString());
            //object rsult = xmlData.Data;
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value as string;
            int  resultDateTime;
            if (int.TryParse(strValue, out resultDateTime))
            {
                return resultDateTime;
            }
            return DependencyProperty.UnsetValue;
        }
    }
}
